using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArcherElfBattleState : Enemy_BattleState
{
    private bool reachedDeadEnd;
    private bool canFlip;
    public ArcherElfBattleState(Enemy enemy, StateMachine stateMachine, string animName) : base(enemy, stateMachine, animName)
    {

    }
    public override void Enter()
    {
        base.Enter();
        reachedDeadEnd = false;
    }

    public override void Update()
    {
        if (enemy.IsGround == false || enemy.IsWall)
            reachedDeadEnd = true;

        if (enemy.PlayerDetected())
        {
            UpdateLastTimeWasInBattle();
            UpdateTargetIfNeeded();
        }

        //如果战斗时间结束（脱离战斗时间结束）
        if (BattleTimeIsOver())
            stateMachine.ChangeState(enemy.idleState);

        //判断是否能够攻击
        if (CanAttack())
        {
            //如果未检测到玩家，并且判断当前自身是否能够翻转
            if (enemy.PlayerDetected() == false)
            {
                if (canFlip)
                {
                    enemy.HandleFlip(MoveDirection());
                    canFlip = false;
                }
                else if (reachedDeadEnd == false)
                    enemy.SetVelocity(enemy.battleMoveSpeed * MoveDirection(), rb.velocity.y);
            }
            //如果玩家在敌人攻击范围内并且敌人检测到玩家
            if (WithInAttackRange() && enemy.PlayerDetected())
            {
                canFlip = true;
                lastTimeAttacked = Time.time;
                stateMachine.ChangeState(enemy.attackState); //敌人发动攻击
            }
        }
        else //继续追踪
        {
            //如果玩家没有进入最小追踪范围，持续追踪
            if (IsInMinTrace() == false)
            {
                //判断玩家是否能够移动（没有到达四区，并且距离小于攻击距离的80%）
                bool shouldWalkAway = reachedDeadEnd == false && DistanceToPlayer() < enemy.attackDistance * .8f;

                //如果需要移动，则朝玩家反方向移动
                if (shouldWalkAway)
                    enemy.SetVelocity(-enemy.battleMoveSpeed * MoveDirection(), rb.velocity.y);
                else
                {
                    //水平速度设置为0
                    enemy.SetVelocity(0, rb.velocity.y);
                    //如果没有检测到玩家
                    if (enemy.PlayerDetected() == false)
                        enemy.HandleFlip(MoveDirection());
                }
            }
        }
    }
}